import { login, logout,getInfo } from '@/api/user'
import { getToken, setToken, removeToken, } from '@/utils/auth'
import { getLocal, setLocal, clearLocal } from '../../utils/common.js'
import {resetRouter} from "@/router";

const getDefaultState = () => {
  return {
    token: getToken(),
    userinfo: getLocal('userInfo') || {},
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_UID: (state, uid) => {
    state.uid = uid
  },
  SET_USERINFO: (state, userinfo) => {
    state.userinfo = userinfo
    setLocal('userInfo', userinfo)
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.token)
        commit('SET_USERINFO', data)
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo().then(response => {
        const { data } = response
        commit('SET_USERINFO', data)
      }).catch(error => {
        reject(error)
      })
      resolve()
    })
  },
  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', null)
        commit('SET_USERINFO', null)
        removeToken()
        resetRouter()
        clearLocal('userInfo')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

